<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of youtubue
 *
 * @author sifat
 * 
 * @doc http://code.google.com/apis/youtube/2.0/developers_guide_protocol_api_query_parameters.html
 */

class youtube extends BaseClass{
    //put your code here
    public $url='https://gdata.youtube.com/feeds/api/videos';
    public $vedioId;
    
    function __construct($data, $EE) {
        parent::__construct($data, $EE);
        
        $this->options=$this->apiOptions('youtube');
        $this->fields=$this->getFields('youtube');
        $this->generateUrl();
    }
    
    function generateUrl(){
        $this->url .= '?q='.urlencode(implode("+", $this->keyword)).'&lang='.$this->options['lang'];
    }
    
    function getData() {
        
        if(!$this->options || !$this->fields){
            return array();
        }
        
        $this->formateData();
        
        if(empty ($this->insertData)){
            return array();
        }
        
        return $this->insertData;
    }
    
    function searchReasults(){
        $youtubeSearchResults=simplexml_load_file($this->url);
        return $youtubeSearchResults->entry;
    }
    
    function formateData(){
        $searchReasults=$this->searchReasults();
        //pr($searchReasults);
        if(!$searchReasults){
            return false;
        }
        //pr($this->options);
        
        $i=0;
        foreach($searchReasults as $result){
            $this->vedioId=array_pop(explode("/", $result->id));
            
            foreach ($this->fields as $key=>$value){
                if (substr($key, 0, strpos($key, '_'))!='fmt'){
                    if(isset ($this->fields['embedcode'])){
                        if($this->fields['embedcode']==1 && $key=='embedcode'){
                            $this->insertData[$i]['field_id_'.$value]='<iframe class="youtube-player" type="text/html" width="'.$this->options['width'].'" height="'.$this->options['height'].'" src="http://www.youtube.com/embed/'.$this->vedioId.'" frameborder="0"></iframe>';
                        }
                        else{
                            $this->insertData[$i]['field_id_'.$value]=(string)$result->$key;
                        }
                    }
                    else{
                        $this->insertData[$i]['field_id_'.$value]=(string)$result->$key;
                    }
                    
                    
                    $this->insertData[$i]['field_ft_'.$value]=  $this->fields['fmt_'.$key];
                    $this->insertData[$i]['title']='youtube-'.implode("&", $this->keyword) . '-at-' . date('Y-m-d', time()) .'-'. rand(0, 9999);
                    $this->insertData[$i]['entry_date']=time();
                }
            }
            $i++;
        }
    }
}
?>
